package cn.well.cloud.modular.auth.controller;

import cn.hutool.core.lang.UUID;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import cn.stylefeng.roses.kernel.model.response.ResponseData;
import cn.well.cloud.base.auth.jwt.JwtAuthResponse;
import cn.well.cloud.base.auth.jwt.JwtTokenUtil;
import cn.well.cloud.base.auth.jwt.payload.JwtPayLoad;
import cn.well.cloud.base.auth.service.AuthService;
import cn.well.cloud.base.oss.server.OSSUtil;
import cn.well.cloud.base.util.OssToImgUtil;
import cn.well.cloud.base.wechat.api.impl.MiniCode2Session;
import cn.well.cloud.core.auth.validator.IReqValidator;
import cn.well.cloud.exception.TipsException;
import cn.well.cloud.exception.annotion.ParamCheck;
import cn.well.cloud.exception.enums.BizExceptionEnum;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求获取token令牌
 * 2019年12月20日
 * @author wison
 *
 */
@RestController
@RequestMapping("/auth")
public class AuthLoginController {
	
	private MiniCode2Session miniCode2Session = new MiniCode2Session();
	
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    @Autowired
    private AuthService authService;
    
    @Autowired
//    private IUserService userService;
    
    
    @Resource(name = "dbValidator")
    private IReqValidator reqValidator;

    @RequestMapping(value = "/login")
    public Object createAuthenticationToken(@ParamCheck String userId, String password) {
        
    	boolean validate = reqValidator.validate(userId, password);

        if (validate) {
            String token = authService.login(userId);
            JwtPayLoad payLoad = jwtTokenUtil.getJwtPayLoad(token);
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("token", token);
            resultMap.put("randomKey", payLoad.getUserKey());
            return ResponseData.success(resultMap);

        } else {
            throw new ServiceException(BizExceptionEnum.AUTH_REQUEST_ERROR);
        }
    }
    
    /**
     * 小程序用户登陆校验 注册或更新session_key 
     * 
     * @param code
     *            小程序用户登录凭证（有效期五分钟）
     * @return 登陆凭证：token(封装着userId) wison 2019年8月14日
     * @throws Exception 
     */

    @RequestMapping("/userLogin")
    @ResponseBody
    public Object userLogin(@ParamCheck String code, String type,String nickName,String avatarUrl, HttpServletRequest request) throws Exception {
        if (ToolUtil.isEmpty(code)) {
            return ResponseData.error(BizExceptionEnum.PARAM_ERROR.getMessage());
        }
        try {
        	
        	String headUrl = getAliServiceHeadUrl(avatarUrl,request);
        	
        	String img = OssToImgUtil.HttpToHttps(headUrl);
        	
            Object obj = miniCode2Session.getUserOpenidAndUnionid(code, type);
//            Long userId = userService.addUser(obj, type,nickName,img);
            Long userId = 1L;
            if(ToolUtil.isEmpty(userId)){
            	return ResponseData.error(BizExceptionEnum.OPENID.getMessage());
            }
            String token = authService.login(userId+""); 
            JwtPayLoad payLoad = jwtTokenUtil.getJwtPayLoad(token);
            JwtAuthResponse ja = new JwtAuthResponse(token,  payLoad.getUserKey());
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("token", token);
            resultMap.put("randomKey", ja.getRandomKey());
            resultMap.put("userId", userId.toString());
            return ResponseData.success(resultMap);
        } catch (TipsException e) {
            e.printStackTrace();
            return ResponseData.error(e.getCode(), e.getMessage());
        }
    }
    
    
    /**
     * 
     * @param headUrl 网络图片地址
     * @return
     */
    @RequestMapping("/getAliServiceHeadUrl")
    @ResponseBody
    public String getAliServiceHeadUrl(String headUrl, HttpServletRequest request) {
        String imgurl = "";
        try {
             // 构造URL
             URL url = new URL(headUrl);
             // 打开连接
             URLConnection con = url.openConnection();
             // 输入流
             InputStream is = con.getInputStream();
             // 1K的数据缓冲
             byte[] bs = new byte[1024];
             // 读取到的数据长度
             int len;
             //获取工作空间地址
             String path = request.getSession().getServletContext().getRealPath("");//request.getContextPath();//request.getRequestURL().toString();
             Date d=new Date();
             String imgName = d.getTime()+".jpg";//+".png";
             imgName = path + "assets\\"+imgName;
             File file = new File(path);// (String) property.get("ewmPath"));
             if (!file.exists()) {
                 file.mkdirs();
             }
             // 输出的文件流
             OutputStream os = new FileOutputStream(imgName);
             // 开始读取
             while ((len = is.read(bs)) != -1) {
                 os.write(bs, 0, len);
             }
             //获取文件流
             File deletefile = new File(imgName);
             
             // 把图片读入到内存中
             BufferedImage bufImg = ImageIO.read(deletefile);
             
             // 压缩代码
             //设置初始化的压缩率为1
             float ratio = 0.1f ;
             //设置压缩后的图片宽度为80
             //float width = 80f;
             
             
             //获取原图片的宽度、高度
             //float ImgWith=bufImg.getWidth();
             //float ImgHight=bufImg.getHeight();
             
             //根据原始图片宽度，与压缩图宽度重新计算压缩率
             /*if (ImgWith>width) {
                 ratio=width/ImgWith;
             }
*/             
             //file转byte[]
             byte[] buffer = null;
             FileInputStream fis = new FileInputStream(deletefile);  
             ByteArrayOutputStream bos = new ByteArrayOutputStream();  
             
             //bufImg = Thumbnails.of(bufImg).scale(ratio).asBufferedImage();
            
             bufImg = Thumbnails.of(bufImg).size(bufImg.getWidth(), bufImg.getHeight()).outputQuality(0.7).asBufferedImage();
             
             /*byte[] b = new byte[1024];  
             int n;  
             while ((n = fis.read(b)) != -1)  
             {  
                 bos.write(b, 0, n);  
             } */ 
             
             ImageIO.write(bufImg,"jpg",bos);
             
             fis.close();  
             bos.close();  
             buffer = bos.toByteArray();
             //上传阿里云
             String filename = "ffyy/sn/"+ UUID.randomUUID()+ ".jpg";

             OSSUtil.upload(filename, buffer);
             String path1 = OSSUtil.getDownloadUrl();
             filename = path1+ "/" + filename;
             imgurl = filename;
             // 完毕，关闭所有链接
             os.close();
             is.close();
             deletefile.delete();
             System.out.println("success");
         } catch (Exception e) {
             System.out.println("error");
         }
        return imgurl;
    }
    
}
